import Vue from 'vue'
import Socket from './utils/socket'

export default new Vue({
    data() {
        return {
            login:false,
            io:null,
            users: [],
            groups: [],
            RC4KEY: '',
            msgs: []
        }
    },
    watch:{
        login(val, oldVal) {
            if (val) {
                this.RC4KEY = Math.random().toString(8).substring(2,8);
            }
        }
    },
    methods: {
        initIo(params, callback) {
            const { userid } = params;
            this.io = new Socket(params);
            this.io.onJoined(r => {
                const { userid } = r;
                const ids = this.users.findIndex(user => userid == user.userid);
                if (ids>-1) {
                    this.users[ids].online = true;
                }
            })
            this.io.onLeft(r => {
                const { userid } = r;
                const ids = this.users.findIndex(user => userid == user.userid);
                this.users[ids].online = false;
            })
            this.io.onSend('get users')
            this.io.onAll(r => {
                this.users = r.map(t => {
                    return {
                        ...t,
                        recent: '',
                        msg: []
                    }
                }).sort((a, b)=> b.online - a.online)
            })
            callback()
            this.io.onFail(() => {
                this.login = false ;
                this.io.disconnect()
            })
            this.io.socket.on('add friend', (r) => {
                const uid = this.users.findIndex(t => t.userid === r.friend);
                const mid = this.msgs.findIndex(t => t.friend ===r.friend);

                if (uid<0&&mid<0) {
                    this.msgs.push(r)
                }
                if (mid>=0) {
                    console.log('不可重复添加')
                }
            })
            this.io.socket.on('pass friend', r => {
                this.$message.success(`${r.username}通过了好友请求！`)
                this.users.push({
                    ...r,
                    recent: '',
                    msg: []
                })
            })
            this.io.socket.on('update user', x => {
                const up = this.users.findIndex(z => z.userid == x.userid)
                if (up>-1) {
                    const ninfo = {...this.users[up], ...x}
                    this.users.splice(up, 1, ninfo) 
                    // this.$set('users', up, ninfo)
                }
            })

            this.io.socket.on('all group', g => {
                this.groups = g.map(t => {
                    return {
                        ...t,
                        recent: '',
                        msg: []
                    }
                })
            })
        }
    }
})
